package com.enjoyor.soa.traffic.server.tsms.dubbo.impl;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.dubbo.config.annotation.Service;
import com.enjoyor.soa.traffic.api.dto.tsms.RouteInfoDto;
import com.enjoyor.soa.traffic.api.service.dubbo.tsms.IDubboSchemeRehearseService;
import com.enjoyor.soa.traffic.core.tsms.domain.SchemeInfo;
import com.enjoyor.soa.traffic.core.tsms.service.IRouteInfoService;
import com.enjoyor.soa.traffic.core.tsms.service.ISchemeInfoService;
import com.enjoyor.soa.traffic.server.tsms.common.RehearseGlobal;
import com.enjoyor.soa.traffic.server.tsms.handler.RehearseClashHandler;
import com.enjoyor.soa.traffic.server.tsms.thead.RehearseThead;
import com.enjoyor.soa.traffic.util.helper.GeoToolsHelper;
import com.enjoyor.soa.traffic.util.helper.ResultHelper;
import com.enjoyor.soa.traffic.util.helper.TimeHelper;
import com.enjoyor.soa.traffic.util.pojo.ResultPojo;

@Service(version = "1.0.0", timeout = 4000)
public class DubboSchemeRehearseService implements IDubboSchemeRehearseService {
	//private static final Logger logger = Logger.getLogger(DubboSchemeRehearseService.class);
	@Autowired
	private ISchemeInfoService iSchemeInfoService;
	@Autowired
	private IRouteInfoService iRouteInfoService;
	GeoToolsHelper geoToolsHelper = new GeoToolsHelper();

	@Autowired
	private DubboServerPushServiceImpl dubboServerPushServiceImpl;
	//List<RehearseThead> threadlist = new ArrayList<>(); //存储预演线程名的list
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	DecimalFormat df= new DecimalFormat("#0.00");
	//线路拆分时间间隔
	public static int routeSplitTime;
	@Value("${route.split.time}")
	public void setRouteSplitTime(int routeSplitTime) {
		this.routeSplitTime = routeSplitTime;
	}
	//冲突校验的时间间隔数
	public static int timeNum;
	@Value("${route.clash.time.num}")
	public void setTimeNum(int timeNum) {
		this.timeNum = timeNum;
	}
	//车队冲突距离
	public static int clashDistance;
	@Value("${route.clash.distance}")
	public void setClashDistance(int clashDistance) {
		this.clashDistance = clashDistance;
	}
	//设备锁定距离
	public static int lockDistance;
	@Value("${device.lock.distance}")
	public void setLockDistance(int distance) {
		this.lockDistance = distance;
	}
	
	/**
	 * 冲突检测方法
	 * @param schemeBeginDate 方案开始日期 
	 * @param schemeEndDate 方案结束日期 
	 * @return 方案冲突的时间段
	 * */
	@SuppressWarnings({ "unchecked" })
	@Override
	public ResultPojo getSchemeRehearseList(String browserId, String schemeBeginDate, String schemeEndDate, 
			boolean isDetail) { 
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		try {
			resultList = (List<Map<String, Object>>) iSchemeInfoService.getPreviewSchemeList(schemeBeginDate, 
					schemeEndDate, isDetail);
			for (int i = 0; i < resultList.size(); i++) { // 多天
				String executeDate = (String) resultList.get(i).get("executeDate"); // 执行日期
				long executeDateLong = TimeHelper.StringToDateTime(executeDate, "yyyy-MM-dd");//执行日期转化为时间戳
				String nowDate = TimeHelper.dateToString(new Date(), "yyyy-MM-dd");
				long nowDateLong = TimeHelper.StringToDateTime(nowDate, "yyyy-MM-dd");//当天日期转化为时间戳
				//大于当天日期
				if(executeDateLong >= nowDateLong) {
					List<SchemeInfo> schemeList = (List<SchemeInfo>) resultList.get(i).get("schemeList"); // 当天多个方案
					//模拟方案执行冲突
					Map<String, Object> m=new HashMap<>();
					m.put("browserId",browserId);
					m.put("executeDate",executeDate);
					m.put("schemeList",schemeList);
					m.put("routeSplitTime",routeSplitTime);
					//m.put("dubboServerPushServiceImpl",dubboServerPushServiceImpl);
					//m.put("iRouteInfoService",iRouteInfoService);
					m.put("isDetail",isDetail);
					RehearseClashHandler.getInstance().handle(m);
					/*RehearseClashThead clashThead = new RehearseClashThead(browserId, executeDate, schemeList, routeSplitTime, 
							dubboServerPushServiceImpl, iRouteInfoService, isDetail);
					clashThead.setName(browserId+"_"+executeDate);
					clashThead.start();*/
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ResultHelper.getResult(resultList);

	}
	
	/**
	 * 返回ServerPush的url地址
	 */
	@Override
	public ResultPojo getPushServerUrl() {
		return dubboServerPushServiceImpl.getBasePath();		
	}
	
	/**
	 *   预演,推送
	 * 
	 * @param rout 进度百分比 
	 * @param date 日期   
	 * @param times 倍率
	 * @param browserId   浏览器id 
	 * @param state   状态(start/stop/suspend)
	 * @param isrout   是否只改变进度 
	 */
	@Override
	public void getPushServer(double rout, String executeDate, double times, String state, String browserId, 
			boolean isrout, List<RouteInfoDto> routeInfoDtoList) {
		RehearseThead rehearseThread = null; // 预演线程
		//遍历线程列表，查询是否存在
		for (Thread t : RehearseGlobal.rehearseThreadlist) {
			if (t != null) {
				if (t.getName().contains(browserId)) {
					rehearseThread = (RehearseThead) t;
					break;
				}
			}
		}
		
		if (rehearseThread != null) {
			if (state.equals("start")) {  //重新开始
				//修改预演倍速
				rehearseThread.setTimes(times);
				//修改进度
				rehearseThread.setRout(rout);
				rehearseThread.setResume();
				if(routeInfoDtoList != null && routeInfoDtoList.size() > 0) {
					rehearseThread.changeRoute(routeInfoDtoList);
				}
			}
			if (state.equals("stop")) {  //停止
				rehearseThread.setStop();
				rehearseThread.interrupt();
				//移除线程
				Iterator<RehearseThead> iterator = RehearseGlobal.rehearseThreadlist.iterator();
				while (iterator.hasNext()) {
					RehearseThead thread = iterator.next();
					if (thread.getName().contains(browserId)) {
						iterator.remove();
					}
				}
			}
			if (state.equals("suspend")) {   //暂停
				rehearseThread.setSuspend();
			}
		} else { // 新的开始
			if (state.equals("start")) {
				RehearseThead rehearseThread1 = new RehearseThead(executeDate, rout, times, browserId, 
						routeSplitTime, dubboServerPushServiceImpl, iSchemeInfoService, iRouteInfoService, routeInfoDtoList);
				rehearseThread1.setName(browserId);
				rehearseThread1.start();
				RehearseGlobal.rehearseThreadlist.add(rehearseThread1);
			}
		}
	}	

}